<!--
  智慧社区管理系统 - 维修工单详情弹窗
  @author Wu.Liang
  @date 2025-01-30
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="维修工单详情"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-if="repairOrder" class="detail-content">
      <!-- 基本信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单号">{{ repairOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="维修标题">{{ repairOrder.title }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ repairOrder.userName }}</el-descriptions-item>
          <el-descriptions-item label="社区">{{ repairOrder.communityName }}</el-descriptions-item>
          <el-descriptions-item label="房户信息">{{ repairOrder.householdInfo || '--' }}</el-descriptions-item>
          <el-descriptions-item label="维修地址">{{ repairOrder.repairAddress }}</el-descriptions-item>
          <el-descriptions-item label="维修类型">
            <el-tag :type="getRepairTypeTagType(repairOrder.repairType)">
              {{ getRepairTypeText(repairOrder.repairType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="紧急程度">
            <el-tag :type="getUrgencyTagType(repairOrder.urgencyLevel)">
              {{ getUrgencyText(repairOrder.urgencyLevel) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag :type="getStatusTagType(repairOrder.status)">
              {{ getStatusText(repairOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ repairOrder.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(repairOrder.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(repairOrder.updateTime) }}</el-descriptions-item>
          <el-descriptions-item label="处理时长">{{ formatProcessingTime(repairOrder.processingTime) }}</el-descriptions-item>
          <el-descriptions-item v-if="repairOrder.assignTo" label="维修人员">{{ repairOrder.repairmanName || '--' }}</el-descriptions-item>
          <el-descriptions-item v-if="repairOrder.assignTime" label="分配时间">{{ formatDateTime(repairOrder.assignTime) }}</el-descriptions-item>
          <el-descriptions-item v-if="repairOrder.completionTime" label="完成时间">{{ formatDateTime(repairOrder.completionTime) }}</el-descriptions-item>
          <el-descriptions-item v-if="repairOrder.satisfactionScore" label="满意度评分">
            <el-rate 
              :model-value="repairOrder.satisfactionScore" 
              :max="5"
              disabled
              show-score
              text-color="#ff9900"
            />
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 维修内容 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>维修内容</span>
          </div>
        </template>
        <div class="description-content">
          {{ repairOrder.description || '暂无描述' }}
        </div>
      </el-card>

      <!-- 故障图片 -->
      <el-card v-if="repairImages && repairImages.length > 0" class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>故障图片</span>
            <span class="image-count">({{ repairImages.length }}张)</span>
          </div>
        </template>
        <WebImageDisplay 
          :images="repairImages"
          display-mode="grid"
          :max-display-count="6"
          :show-image-info="true"
          empty-text="暂无故障图片"
          @image-click="handleImageClick"
          @error="handleImageError"
          @load="handleImageLoad"
        />
      </el-card>

      <!-- 处理进度 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>处理进度</span>
          </div>
        </template>
        <div v-loading="loadingProgress">
          <el-timeline v-if="progressList.length > 0">
            <el-timeline-item
              v-for="progress in progressList"
              :key="progress.id"
              :timestamp="progress.progressTitle"
              placement="top"
              :type="getProgressTimelineType(progress.progressType)"
            >
              <div class="timeline-content">
                <p>{{ progress.progressContent }}</p>
                <p class="timeline-time">{{ formatDateTime(progress.progressTime) }}</p>
                <p v-if="progress.remark && progress.remark.trim()" class="timeline-remark">备注：{{ progress.remark }}</p>
              </div>
            </el-timeline-item>
          </el-timeline>
          <div v-else class="no-progress">
            <p>暂无进度记录</p>
          </div>
        </div>
      </el-card>

      <!-- 备注信息 -->
      <el-card v-if="repairOrder.remark" class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>备注信息</span>
          </div>
        </template>
        <div class="remark-content">
          {{ repairOrder.remark }}
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          v-if="repairOrder && repairOrder.status === 1"
          type="success"
          @click="handleAssign"
        >
          分配工单
        </el-button>
        <el-button
          v-if="repairOrder && repairOrder.status === 3"
          type="primary"
          @click="handleComplete"
        >
          完成工单
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { RepairOrder, RepairProgress } from '../types/repair'
import { repairProgressApi } from '@/api/repair'
import { ElMessage } from 'element-plus'
import WebImageDisplay from '@/components/WebImageDisplay.vue'

// 作者: Wu.Liang

// Props
interface Props {
  modelValue: boolean
  repairOrder: RepairOrder | null
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'assign': [repairOrder: RepairOrder]
  'complete': [repairOrder: RepairOrder]
}>()

// 响应式数据
const progressList = ref<RepairProgress[]>([])
const loadingProgress = ref(false)

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 计算属性：解析图片信息
const repairImages = computed(() => {
  if (!props.repairOrder?.repairImages) {
    return []
  }
  
  try {
    // 如果repairImages是字符串，尝试解析JSON
    if (typeof props.repairOrder.repairImages === 'string') {
      return JSON.parse(props.repairOrder.repairImages)
    }
    
    // 如果repairImages已经是数组，直接返回
    if (Array.isArray(props.repairOrder.repairImages)) {
      return props.repairOrder.repairImages
    }
    
    return []
  } catch (error) {
    console.error('解析图片信息失败:', error)
    return []
  }
})

// 计算属性：图片URL列表（用于预览）
const imageUrlList = computed(() => {
  return repairImages.value.map(image => image.fileUrl)
})

// 监听对话框开启，加载进度数据
watch(() => props.modelValue, (newVal) => {
  if (newVal && props.repairOrder) {
    loadProgressData()
  }
})

// 加载进度数据
const loadProgressData = async () => {
  if (!props.repairOrder?.id) return
  
  try {
    loadingProgress.value = true
    const response = await repairProgressApi.getProgressListByOrderId(props.repairOrder.id)
    if (response.code === 200) {
      // 确保数据按时间排序，并过滤掉无效数据
      const validProgressList = (response.data || []).filter(progress => 
        progress.progressContent && 
        progress.progressContent !== '--' && 
        progress.progressTime
      )
      progressList.value = validProgressList
    } else {
      ElMessage.error('加载进度数据失败')
    }
  } catch (error) {
    console.error('加载进度数据失败:', error)
    ElMessage.error('加载进度数据失败')
  } finally {
    loadingProgress.value = false
  }
}

// 事件处理
const handleClose = () => {
  dialogVisible.value = false
}

const handleAssign = () => {
  if (props.repairOrder) {
    emit('assign', props.repairOrder)
  }
}

const handleComplete = () => {
  if (props.repairOrder) {
    emit('complete', props.repairOrder)
  }
}

// 处理图片点击事件
const handleImageClick = (image: any, index: number) => {
  console.log('图片点击事件:', image, index)
}

// 处理图片错误事件
const handleImageError = (data: { index?: number; image?: any; error: any }) => {
  console.error('图片错误事件:', data)
}

// 处理图片加载事件
const handleImageLoad = (data: { event: any }) => {
  console.log('图片加载事件:', data)
}

// 格式化文件大小
const formatFileSize = (fileSize: number) => {
  if (!fileSize || fileSize === 0) {
    return '0 B'
  }
  
  const units = ['B', 'KB', 'MB', 'GB']
  let size = fileSize
  let unitIndex = 0
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`
}

// 格式化处理时长
const formatProcessingTime = (processingTime: string | number) => {
  if (!processingTime) {
    return '--'
  }
  
  const hours = parseInt(processingTime.toString())
  if (hours === 0) {
    return '小于1小时'
  } else if (hours < 24) {
    return `${hours}小时`
  } else {
    const days = Math.floor(hours / 24)
    const remainingHours = hours % 24
    return `${days}天${remainingHours > 0 ? remainingHours + '小时' : ''}`
  }
}

// 工具函数
const getRepairTypeTagType = (repairType: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'danger',
    5: 'info'
  }
  return typeMap[repairType] || 'info'
}

const getRepairTypeText = (repairType: number) => {
  const typeMap: Record<number, string> = {
    1: '水电',
    2: '门窗',
    3: '电梯',
    4: '消防',
    5: '其他'
  }
  return typeMap[repairType] || '未知'
}

const getUrgencyTagType = (urgencyLevel: number) => {
  const urgencyMap: Record<number, string> = {
    1: 'danger',
    2: 'warning',
    3: 'info'
  }
  return urgencyMap[urgencyLevel] || 'info'
}

const getUrgencyText = (urgencyLevel: number) => {
  const urgencyMap: Record<number, string> = {
    1: '紧急',
    2: '一般',
    3: '不紧急'
  }
  return urgencyMap[urgencyLevel] || '未知'
}

const getStatusTagType = (status: number) => {
  const statusMap: Record<number, string> = {
    1: 'warning',
    2: 'info',
    3: 'primary',
    4: 'success',
    5: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '待受理',
    2: '已受理',
    3: '维修中',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || '未知'
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '--'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取进度时间线类型
const getProgressTimelineType = (progressType: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',  // 工单创建
    2: 'success',  // 工单受理 
    3: 'warning',  // 开始维修
    4: 'success',  // 维修完成
    5: 'danger'    // 工单取消
  }
  return typeMap[progressType] || 'info'
}
</script>

<style lang="scss" scoped>
.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }

  .card-header {
    font-weight: 600;
    color: #303133;
  }
}

.description-content {
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-all;
}

.remark-content {
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-all;
}

.timeline-content {
  p {
    margin: 0;
    line-height: 1.5;
    
    &.timeline-time {
      font-size: 12px;
      color: #909399;
      margin-top: 4px;
    }

    &.timeline-remark {
      font-size: 12px;
      color: #666;
      margin-top: 4px;
      font-style: italic;
    }
  }
}

.no-progress {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

.image-count {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.image-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  }
}

.image-preview {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.image-info {
  padding: 8px 12px;
  background: #fafafa;
  
  .image-name {
    display: block;
    font-size: 12px;
    color: #606266;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .image-size {
    display: block;
    font-size: 11px;
    color: #909399;
  }
}
</style> 